package doc2db;

import doc2db.interfaces.xmledit.HelpFrame;
import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;
import javax.swing.Icon;
import javax.swing.ImageIcon;

public class Launcher {
    public static final String RESOURSE_DIR = "/doc2db/resources/";
    public static final String RESOURSE_PATH = RESOURSE_DIR + "Launcher.properties";

    private static final Properties properties ;
    private static Map<String, Icon> icons = new HashMap<String, Icon>();

    static {
        properties = new Properties();
        try {
            Class<Launcher> aClass = Launcher.class;
            properties.load(aClass.getResourceAsStream(RESOURSE_PATH));
        } catch (IOException ex) {
            System.err.println("fatal error on load properties: " + RESOURSE_PATH);
        }
    }

    public static Icon getIcon(String key) {
        Icon get = icons.get(key);
        if (get != null){
            return get;
        }

        String name = properties.getProperty(key);
        if (name == null){
            name = key;
        }

        URL resource = Launcher.class.getResource(RESOURSE_DIR + name);
        if (resource == null){
            System.err.println("now URL '" + RESOURSE_DIR + name + "'");
            return null;
        }

        get = new ImageIcon(resource);
        icons.put(key, get);
        return get;
    }

    public static Image getImage(String key){
        ImageIcon icon = (ImageIcon) getIcon(key);
        if (icon != null){
            return icon.getImage();
        }
        return null;
    }

    public static String getString(String key) {
        return properties.getProperty(key, key);
    }

    public static String getText(String path){
        InputStream stream = HelpFrame.class.getResourceAsStream(RESOURSE_DIR + path);
        if (stream == null){
            return null;
        }
        Scanner scan = new Scanner(stream);
        StringBuilder str = new StringBuilder();
        while (scan.hasNextLine()) {
            str.append(scan.nextLine()).append("\n");
        }
        return str.toString();
    }

}
